import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, DatePicker, Table } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getOrderList, sendRefund } from '@/services/order/refund'

const { TabPane } = Tabs

const { Option } = Select

const { RangePicker } = DatePicker

// 表头
const columns = [
  {
    title: '申请单号',
    dataIndex: 'applyNo',
    key: 'applyNo',
    align: 'center',
  },
  {
    title: '订单号',
    dataIndex: 'orderNo',
    key: 'orderNo',
    align: 'center'
  },
  {
    title: '下单时间',
    dataIndex: 'amdOrderInfo.orderTime',
    key: 'amdOrderInfo.orderTime',
    align: 'center'
  },
  {
    title: '支付时间',
    dataIndex: 'amdOrderInfo.payTime',
    key: 'amdOrderInfo.payTime',
    align: 'center'
  },
  {
    title: '商品名称',
    dataIndex: 'amdOrderDetailInfo.goodsName',
    key: 'amdOrderDetailInfo.goodsName',
    align: 'center'
  },{
    title: '商品单价',
    dataIndex: 'amdOrderInfo.originalPrice',
    key: 'amdOrderInfo.originalPrice',
    align: 'center'
  },
  {
    title: '商品数量',
    dataIndex: 'amdOrderDetailInfo.goodsNums',
    key: 'amdOrderDetailInfo.goodsNums',
    align: 'center'
  },
  {
    title: '实付金额',
    dataIndex: 'amdOrderInfo.actualPrice',
    key: 'amdOrderInfo.actualPrice',
    align: 'center'
  },
  {
    title: '收货人',
    dataIndex: 'amdOrderInfo.amdOrderAddressInfo.contactName',
    key: 'amdOrderInfo.amdOrderAddressInfo.contactName',
    align: 'center'
  },
  {
    title: '收货电话',
    dataIndex: 'amdOrderInfo.amdOrderAddressInfo.contactPhone',
    key: 'amdOrderInfo.amdOrderAddressInfo.contactPhone',
    align: 'center'
  }
]

const Refund = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [orderList, setOrderList] = useState([])
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [refundStatus, setRefundStatus] = useState('REFUND_NO')
  const [statusList, setStatusList] = useState([
    {
      id: 'REFUND_NO',
      name: '未退款'
    },
    {
      id: 'REFUND_YES',
      name: '已退款'
    },
    {
      id: 'REFUND_EXCEPTION',
      name: '未退款'
    }
  ])
  const [auditStartTime, setAuditStartTime] = useState('')
  const [auditEndTime, setAuditEndTime] = useState('')

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }
  // 选择时间
  const selectData = (date, dateString) => {
    setAuditStartTime(dateString[0])
    setAuditEndTime(dateString[1])
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      let params = {
        pageNo: page,
        pageSize,
        refundStatus
      }
      getOrderLists(params)
    }
  }
  // 切换页面
  const changeTab = async value => {
    let status
    let params = {
      pageNo,
      pageSize,
      refundStatus: ''
    }
    switch (value) {
      // 退款待发放
      case '1':
        status = 'REFUND_NO'
        params.refundStatus = status
        await getOrderLists(params)
        break
      // 退款发放记录
      case '2':
        status = 'REFUND_YES'
        params.refundStatus = status
        await getOrderLists(params)
        break
      // 退款发放异常
      case '3':
        status = 'REFUND_EXCEPTION'
        params.refundStatus = status
        await getOrderLists(params)
        break
    }
    setRefundStatus(status)
    handleReset()
  }

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    let params = {
      pageNo,
      pageSize,
      refundStatus
    }
    await getOrderLists(params)
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        pageNo,
        pageSize,
        auditStartTime,
        auditEndTime
      }
      Object.assign(params, values);
      await getOrderLists(params)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="申请单号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('applyNo', {})
              (<Input placeholder="请输入申请单号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="订单号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('orderNo', {})
              (<Input placeholder="请输入订单号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="商品名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('goodsName', {})
              (<Input placeholder="请输入商品名称" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="买家信息" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('userName', {})
              (<Input placeholder="请输入买家信息" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="收货人" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('receiveName', {})
              (<Input placeholder="请输入收货人" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="货物单号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('trafficNo', {})
              (<Input placeholder="请输入货物单号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="退款状态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('refundStatus', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { statusList && statusList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="审核时间" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('date', {})
              (<RangePicker onChange={selectData} />)}
          </Form.Item>
        </Col>
      </Row>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    switch (type) {
      // 发放
      case 1:
        if (refundStatus !== 'REFUND_NO') {
          alert('仅支持待发放状态订单')
        }
        if (JSON.stringify(record) === '{}') {
          return
        }
        await sendRefunds()
        break
    }
  }
  // 获取订单列表
  const getOrderLists = async (params) => {
    let res = await getOrderList(params)
    if (res.code === '0') {
      setOrderList(res.data)
      setTotal(res.iTotalRecords)
    } else {
      alert('您点击的太快了, 请稍后尝试')
    }
  }
  // 发放退款
  const sendRefunds = async () => {
    let params = {
      applyNo: record[0].applyNo,
      refundChannel: 'ORIGINAL_BACK'
    }
    let res = await sendRefund(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Tabs defaultActiveKey="1" onChange={changeTab}>
        <TabPane tab="退款待发放" key="1">
        </TabPane>
        <TabPane tab="退款发放记录" key="2">
        </TabPane>
        <TabPane tab="退款发放异常" key="3">
        </TabPane>
      </Tabs>
      <Table
        columns={columns}
        dataSource={orderList}
        rowKey={record => record.applyNo}
        pagination={pagination}
        rowSelection={rowSelection}
      />
   </PageHeaderWrapper>
  )
}

export default Form.create()(Refund)
